package org.lewis.common.jobs;

import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lewis.common.domain.EmailTask;
import org.lewis.common.email.MailSender;
import org.lewis.common.service.EmailTaskService;
import org.lewis.woman.service.EmailTaskServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.tocersoft.framework.core.utils.PropertiesUtils;

public class SendEmailJob implements Job{
	
	private EmailTaskService emailTaskService;
	
	public SendEmailJob(){
		emailTaskService=new EmailTaskServiceImpl();
	}
	
	private static final Log LOG=LogFactory.getLog(SendEmailJob.class);

	@Override
	public void execute(JobExecutionContext jec) throws JobExecutionException {
		LOG.info("SendEmailJob running...");
		Properties properties = new Properties();
		properties.put("email.hostname", PropertiesUtils.getValue("email.hostname"));
		properties.put("email.loginname", PropertiesUtils.getValue("email.loginname"));
		properties.put("email.loginpwd", PropertiesUtils.getValue("email.loginpwd"));
		properties.put("email.personal", PropertiesUtils.getValue("email.personal"));
		List<EmailTask> emailTaskList=emailTaskService.queryEmailTaskByStatus(EmailTask.STATUS.init.name(), 1, 500);
		for (EmailTask emailTask : emailTaskList) {
			if(EmailTask.SENDTYPE.immediately.name().equals(emailTask.getSendType())){//立即发送
				send(properties, emailTask);
			}else if(EmailTask.SENDTYPE.plan.name().equals(emailTask.getSendType())){
				if(null!=emailTask.getPlanSendTime()){
					Calendar cal=Calendar.getInstance();
					if(emailTask.getPlanSendTime().after(cal.getTime())){//已经超过了计划发送时间，则立即发送
						send(properties, emailTask);
					}else{
						Calendar cal2=Calendar.getInstance();
						cal2.setTime(emailTask.getPlanSendTime());
						if(cal.getTimeInMillis()<=cal2.getTimeInMillis()+1000*60*5){
							send(properties, emailTask);
						}
					}
				}
			}
		}
	}

	private void send(Properties properties, EmailTask emailTask) {
		if(StringUtils.isNotBlank(emailTask.getReceiver())
		  &&StringUtils.isNotBlank(emailTask.getContent())){
			LOG.info("SendEmail to:"+emailTask.getReceiver()+",Subject:"+emailTask.getSubject());
			MailSender.send(properties, emailTask.getReceiver(), emailTask.getSubject(), emailTask.getContent(),"text/html");
			//更新短信发送状态，发送时间
			emailTaskService.updateEmailTaskStatusAndTime(emailTask.getId());
		}
	}

}
